<template>
  <div class="line-chart" :style="style">
    <KCharts
      ref="lineChartRef"
      :width="width"
      :height="height"
      :option="option"
      v-bind="$attrs"
      over
      @out="$emit('out')"
      @over="$emit('over', $event)"
      @click="$emit('clicked', $event)"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { createLineOption } from '@/hooks/charts/line-chart';
import type {
  Options,
  XType,
  YType,
  BaseNameDataObject
} from '@/hooks/charts/type';

defineOptions({ name: 'LineChart' });

interface YData extends BaseNameDataObject {
  tooltipTitles?: string[];
}
interface Props {
  width: string;
  height: string;
  grid?: any;
  legend?: any;
  tooltip?: Function;
  options?: Options;
  xType: XType;
  yType: YType;
  xData: number[] | string[];
  yData: YData[];
}
const props = withDefaults(defineProps<Props>(), {
  grid: {},
  legend: {},
  tooltip: undefined,
  options: () => {
    return {
      showLegend: true,
      legendPosition: 'top',
      showLabel: true,
      labelLimit: 0
    };
  }
});
defineEmits(['clicked', 'out', 'over']);
const option = ref({});
const lineChartRef = ref();
const style = computed(() => {
  return {
    width: props.width,
    height: props.height
  };
});

watch(
  () => props.yData,
  (yData) => {
    if (!yData?.length) {
      return;
    }

    // 大屏类应用场景，当yData变化，保证图表重新渲染时原本选中的legend不会因此变化
    let selected = {};
    if (lineChartRef.value) {
      selected = lineChartRef.value?.chartsRef?.getOption?.()?.legend?.[0]?.selected;
    }
    option.value = createLineOption({
      selected,
      grid: props.grid,
      legend: props.legend,
      tooltip: props.tooltip,
      options: props.options ?? {},
      xType: props.xType,
      yType: props.yType,
      xData: props.xData,
      yData
    });
  },
  {
    deep: true,
    immediate: true
  }
);
</script>

<style lang="scss" scoped>
.line-chart {
  box-sizing: border-box;
}
</style>
